<template>
    <view class="bg-white login min-h-full flex flex-col items-center px-[40rpx] pt-[80rpx] box-border">
        <view class="user-info flex px-[50rpx] justify-between py-[50rpx]">
            平台登录
            <!-- <u-image src="@/static/images/logo/logo.png" height="200" width="480" /> -->
        </view>
        <view class="w-full mt-[60rpx] pb-[60rpx]">
            <!-- #ifndef MP-WEIXIN -->
            <u-form borderBottom>
                <u-form-item borderBottom>
                    <u-icon class="mr-2" :size="36" name="/static/images/icon/icon_user.png" />
                    <u-input class="flex-1" v-model="formData.username" :border="false" placeholder="请输入手机号" />
                </u-form-item>
                <u-form-item borderBottom>
                    <u-icon class="mr-2" :size="36" name="/static/images/icon/icon_password.png" />
                    <u-input class="flex-1" v-model="formData.password" type="password" placeholder="请输入密码"
                        :border="false" />
                </u-form-item>
                <u-form-item borderBottom>
                    <u-input class="flex-1" v-model="formData.code" placeholder="请输入密码" :border="false" />
                    <image class="yzm-right" :src="codeData.codeUrl" @click="getCode"></image>
                </u-form-item>
            </u-form>
            <view class="mt-[60rpx]">
                <u-button type="primary" shape="circle" @click="handleLogin(formData)">
                    登 录
                </u-button>
            </view>
            <view class="text-content flex justify-between mt-[40rpx]">
                <view class="flex-1">
                    <navigator url="/pages/login/forgetPwd" hover-class="none">忘记密码</navigator>
                </view>
                <navigator url="/pages/login/register" hover-class="none">注册账号</navigator>
            </view>
            <!-- #endif -->
            <!-- #ifdef MP-WEIXIN -->
            <view class="mt-[80rpx]" v-if="isWeixin">
                <u-divider>一键登录</u-divider>
                <div class="flex justify-center mt-[40rpx]">
                    <div v-if="isWeixin" class="flex flex-col items-center" @click="wxLogin">
                        <img src="@/static/images/icon/icon_wx.png" class="w-[80rpx] h-[80rpx]" />
                    </div>
                </div>
            </view>
            <!-- #endif -->
        </view>
        <view class="mt-[40rpx]">
            <u-checkbox v-model="isCheckAgreement" shape="circle">
                <view class="flex text-xs">
                    <view>已阅读并同意</view>
                    <view @click.stop>
                        <navigator class="text-primary" hover-class="none" url="/pages/agreement/agreement?type=service">
                            《服务协议》
                        </navigator>
                    </view>
                    <view>和</view>
                    <view @click.stop>
                        <navigator class="text-primary" hover-class="none" url="/pages/agreement/agreement?type=privacy">
                            《隐私协议》
                        </navigator>
                    </view>
                </view>
            </u-checkbox>
        </view>
    </view>
</template>

<script setup lang="ts">
import { getYzmCode, accountLogin, mnpLogin } from '@/api/account'
import { getUserCenter } from '@/api/user'
import { useLockFn } from '@/hooks/useLockFn'
import { useUserStore } from '@/stores/user'
import { isWeixinClient } from '@/utils/client'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
const isWeixin = ref(true)
const showLoginPopup = ref(false)
// #ifdef H5
isWeixin.value = isWeixinClient()
// #endif

const userStore = useUserStore()
const isCheckAgreement = ref(false)
const loginData = ref<any>({})

const formData = reactive({
    username: "admin",
    password: "admin123",
    rememberMe: false,
    code: '',
    uuid: '',
})

const getCode = async () => {
    const res = await getYzmCode()
    const captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
    if (res.code === 200 && captchaOnOff) {
        codeData.codeUrl = "data:image/gif;base64," + res.img;
        formData.uuid = res.uuid
    }
}

const codeData = reactive({
    codeUrl: '',
    getCode: getCode()
})

const loginFun = async () => {
    try {
        await checkAgreement()
        if (!formData.username) return uni.$u.toast('请输入账号/手机号码')
        if (!formData.password) return uni.$u.toast('请输入密码')
        if (!formData.code) return uni.$u.toast('请输入验证码')
        uni.showLoading({
            title: '请稍后...'
        })
        const { data } = await accountLogin(formData)
        if (data) {
            loginHandle(data)
        }
        uni.hideLoading()
    } catch (error: any) {
        uni.hideLoading()
        uni.$u.toast(error)
    }
}

const loginHandle = async (data: any) => {
    const { access_token } = data
    userStore.login(access_token)
    await userStore.getUser()
    uni.$u.toast('登录成功')
    uni.redirectTo({
        url: '/pages/home/index'
    })
}

const { lockFn: handleLogin } = useLockFn(loginFun)

const checkAgreement = async () => {
    if (!isCheckAgreement.value)
        return Promise.reject('请勾选底部已阅读并同意《服务协议》和《隐私协议》')
}
const { lockFn: wxLogin } = useLockFn(async () => {
    try {
        await checkAgreement()
        // #ifdef MP-WEIXIN
        uni.showLoading({
            title: '请稍后...'
        })
        const { code }: any = await uni.login({
            provider: 'weixin'
        })
        const data = await mnpLogin(code)
        loginData.value = data
        const { access_token } = data

        // 临时用户没有昵称
        userStore.login(access_token)
        const res = await getUserCenter()
        if (!res.data.appUser.nickname) {
            uni.hideLoading()
            userStore.temToken = access_token
            showLoginPopup.value = true
            return
        }
        loginHandle(data)
        // #endif
    } catch (error) {
        uni.$u.toast(error)
    }
})

onShow(async () => {
    try {
        if (userStore.isLogin) {
            uni.showLoading({
                title: '请稍后...'
            })
            await userStore.getUser()
            uni.hideLoading()
            uni.navigateBack()
        }
    } catch (error: any) {
        uni.hideLoading()
    }
})

onLoad(async () => {
    // 清空用户信息
    userStore.logout()
    if (userStore.isLogin) {
        // 已经登录 => 首页
        uni.reLaunch({
            url: '/pages/home/index'
        })
        return
    }
})
</script>

<style lang="scss">
page {
    height: 100%;

    .yzm-right {
        width: 8em;
        height: 2.4em;
    }
}
</style>
